package up.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
import up.service.SaveService;

import java.util.List;
import java.util.stream.Collectors;

@RestController
public class UpLoadController {

    @Autowired
    private SaveService saveService;

    /**
     * 初始化目录
     * @return
     */
    @GetMapping("init")
    public String init(){
        saveService.init();
        return "success";
    }


    /**
     * 测试递归删除方法(包括upload目录也会删除)
     * @return
     */
    @DeleteMapping("del")
    public String del(){
        saveService.deleteAll();
        return "success";
    }


    /********************************************************************************************************/

    /**
     * 文件上传功能
     * @param file
     * @return
     */
    @PostMapping("file")
    public String upload(@RequestParam("file") MultipartFile file){
        saveService.save(file);
        return "success";
    }


    /**
     * 文件下载功能
     * @param filename
     * @return
     */
    @GetMapping("/files/{filename:.+}")
    public ResponseEntity<Resource> serveFile(@PathVariable String filename) {
        Resource file = saveService.loadAsResource(filename);
        return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"").body(file);
    }


    /********************************************************************************************************/


    @GetMapping("/")
    public List<String> list() {
        return saveService.loadAll().map(path -> MvcUriComponentsBuilder.fromMethodName(UpLoadController.class,
                                        "serveFile",
                                         path.getFileName().toString()).build().toString())
                .collect(Collectors.toList());
    }

}
